<?php namespace Home\Controller; 

use Hdphp\Controller\Controller;
use \Common\Model\Cate;
use \Common\Model\Goods;
use \Common\Model\GoodsAttr;
use \Common\Model\TypeAttr;

class ListController extends Controller{
    //动作
    public function index(){
		//1.获取分类表
    	$cateModel = new Cate; 
		//2.通过当前分类的cid获得所有子集的cid
		$cid = q('get.cid',null,'intival');
		$cids = $cateModel->getSon($cateModel->get(),$cid);
		$cids[] = $cid;
		
		
		//3.根据cid获得商品的gid
		$goodsModel = new Goods;
		$gids = $goodsModel->where("cate_cid IN(".implode(',', $cids).")")->lists('gid');
		
		//4.通过gid到goods_attr表查询属性	关联属性
		//判断分类下商品是否存在(存在)
		if($gids){		
			$goodsAttrModel = new GoodsAttr;
			$goodsAttr = $goodsAttrModel->where("goods_gid IN(".implode(',', $gids).")")->groupBy('gvalue')->get();
			
			//把相同trid的属性放在了一起，便于前台遍历
			$sameTrid = [];
			foreach($goodsAttr as $v){
				$sameTrid[$v['type_attr_trid']][] = $v;
			}
			
			//组合属性名字和值
			$sameType = [];
			$TypeAttrModel = new TypeAttr;			
			foreach($sameTrid as $k=>$v){
				$sameType[]= [
					'name'=>$TypeAttrModel->where('trid',$k)->pluck('trname'),
					'value'=>$v
				];
			}
			View::with('sameType',$sameType);	

			//5.筛选结果
			//5_1.地址栏效果0_0_...	获取该分类下属性总个数
			$num = count($sameType);
			//用给定值填充数组
			$param = isset($_GET['param']) ? explode('_',$_GET['param']) : array_fill(0,$num,0); 
			View::with('param',$param);			
            //5_2.筛选操作,最终获得商品gid
			$finalGids = $this->filter($param,$gids);	
			
			//商品总数
			$goodsCount = count($finalGids);
			View::with('goodsCount',$goodsCount);	

			//6.商品列表	
			if($finalGids){
				$goodsData = $goodsModel
								->where("gid IN(".implode(',', $finalGids).")")
								->get();	
				View::with('goodsData',$goodsData);	
			}				
		}else{
			View::with('sameType',[]);											
		}	
		
		//顶级分类 (当前位置)
		$cateModel = new \Common\Model\Cate;  	
		$topCate = $cateModel->where("pid=0 AND cid={$cid}")->orderBy('sort','ASC')->find();
		View::with('topCate',$topCate);										
			
    	View::make();
    }

	//获得商品
	public function filter($param,$gids){
		$goodsAttr = new GoodsAttr;
		//获取条件允许的gid
		$gidAll = [];
		foreach($param as $gaid){
			//如果点击的不是"不限"的时候，即有选中条件
			if($gaid){
				//查询到商品属性的名称
				$gvalue = $goodsAttr->where('gaid',$gaid)->pluck('gvalue');
				//该属性名称可能包含多个商品
				$gidAll[] = $goodsAttr->where('gvalue',$gvalue)->lists('goods_gid');
			}
		}
//		p($gidAll);
		//如果$gidAll有值的时候,也就是用户不是全部"不限"的时候
		if($gidAll){
			//取筛选出商品的交集		先取第一个数组
			$gid =  $gidAll[0];
			foreach($gidAll as $v){
				$gid = array_intersect($v, $gid);								
			}
			//因为$gid有可能是其他分类的gid,那么为了确保是当前分类,再次取交集
			$finalGids = array_intersect($gid, $gids);
		}else{
			//如果全部是"不限"的时候(默认状态下)
			$finalGids = $gids;
		}
		return $finalGids;
	}
}
